/**
 * Basic logic for the internal representation of a graph
 */
GraphApp.Traverse = (function () {
	var Queue;
	
	Queue = function () {
		this.memory = [];
	};
	
	Queue.prototype = {
		enqueue : function (elem) {
			this.memory.push(elem);
		},
		
		dequeue : function (elem) {
			return this.memory.shift();
		},
		
		isEmpty : function () {
			return this.memory.length === 0;
		}
	};
	
	Traverse = function (graph) {
		this.graph = graph;
		this.marked = {};
		this.current = {};
		this.state = 0;
		this.searchValue = '';
		this.algorithm = '';
		this.memory = {};
		this.startingPoint = {};
		//this.step = {};
	};
	
	Traverse.prototype = {
		step : function() { 
			// error no algorithm defined
		},
		
		setAlgorithm : function(algorithm) {
			if (algorithm === "BFS") {
				this.algorithm = "BFS";
				this.memory = new Queue();
				this.setStartingPoint(this.startingPoint);
			
				this.step = function() {
					if (this.searchValue === '' || (this.memory.isEmpty() && this.state === 0)) {
						return false;
					}
				
					if (this.state === 0) {
						this.current = this.memory.dequeue();
						if (this.current.value === this.searchValue) {
							return true;
						} else {
							this.state = 1;
							return this.current;
						}
					}
					
					if (this.state === 1) {
						var children = this.graph.neighbors(this.current.id);
						var addmarks = []
						for (var key in children) {
							var node = this.graph.nodes[children[key]];
							if (!this._isMarked(node.id)) {
								addmarks.push(node);
								this._mark(node.id);
								this.memory.enqueue(node);
							}
						}
						this.state = 0;
						return addmarks;				
					}
				}
			} else if (algorithm === "DFS") {
				this.algorithm = "DFS";
				// TODO
			};
		},
		
		setStartingPoint : function(node) {
			this.startingPoint = node;
			if (this.algorithm === "BFS") {
				this.memory.enqueue(node);
				this._mark(node.id);
			} else if (this.algorithm === "DFS") {
				// TODO
			};
		},
		
		setSearchValue : function(value) {
			this.searchValue = value;
		},
		
		_isMarked : function(id) {
			return this.marked[id];
		},
		
		_mark : function(id) {
			this.marked[id] = true;
		}
	};	
	
	return {
		Traverse: Traverse
	};
}());
